<?php
namespace App\Repositories;

use App\Config;
use App\Support\Redis;

class ConfigRepository {

	private $prefix = ":website:config:";

	protected $model, $redis;

	public function __construct(Config $config, Redis $redis) {
		$this->model = $config;
		$this->redis = $redis;
		$this->prefix = config('blog.cache.prefix') . $this->prefix;
	}

	public function getShowConfig() {
		$cache_key = $this->prefix . 'show';
		return $this->cacheConfig($cache_key, ['config'])['config'];
	}

	public function getSeoConfig() {
		$cache_key = $this->prefix . 'seo';
		return $this->cacheConfig($cache_key, ['say', 'title', 'keywords', 'description']);
	}

	public function getContactMe() {
		$cache_key = $this->prefix . 'contact';
		return $this->cacheConfig($cache_key, ['weibo', 'email', 'wechat', 'github']);
	}

	public function getResumeConfig() {
		$cache_key = $this->prefix . 'resume';
		return $this->cacheConfig($cache_key, ['nopwd', 'password']);
	}

	public function clearCache() {
		$this->redis->del($this->prefix . 'all');
		$this->redis->del($this->prefix . 'show');
		$this->redis->del($this->prefix . 'seo');
		$this->redis->del($this->prefix . 'resume');
		$this->redis->del($this->prefix . 'contact');
	}

	public function update($input) {
		$this->model = $this->model->findOrFail(1);
		$this->model->fill($input);
		$this->model->save();
	}

	private function cacheConfig($cache_key, $fields, $minute = 0) {
		if ($this->redis->exists($cache_key)) {
			return $this->redis->hmGet($cache_key);
		}
		$list = $this->getConfigs($fields);
		$this->redis->hMset($cache_key, $list, $minute);
		return $list;
	}

	private function getConfigs($fields = []) {
		$cache_key = $this->prefix . 'all';

		if (!$this->redis->exists($cache_key)) {
			$list = $this->model->orderBy('id', 'ASC')->first();
			if (!$list) {
				abort(500, 'You must run "php artisan db:seed" before you open the website in first time');
			}
			unset($list['id']);
			$this->redis->hMset($cache_key, $list->toArray());
		}

		return $this->redis->hmGet($cache_key, $fields);
	}
}